package com.gravata.enigma;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import android.content.Context;

import com.gravata.enigma.activities.TelaInicial;

public class FtpHelper {

	private Context context;

	private static String HOST;
	private static  String USER;
	private static  String PASS;
	private static int PORT;
	private static FTPClient ftp = new FTPClient();
	public static final String FOLDER_ENIGMA2 = "/etc/enigma2";

	public FtpHelper(Context context) {
		this.context=context;
		HOST=TelaInicial.profile.getUrl();
		USER=TelaInicial.profile.getUsuario();
		PASS=TelaInicial.profile.getSenha();
		PORT=TelaInicial.profile.getPorta();

	}

	public void connect() throws SocketException, IOException{
		// Connect to the SERVER
		ftp.connect(HOST, PORT);
		if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
		}

		// Login to the SERVER
		ftp.enterLocalPassiveMode();
		if (!ftp.login(USER, PASS)) {
		}
		ftp.setFileType(FTP.BINARY_FILE_TYPE);
	}

	public void disconnect(){
		try {
			ftp.logout();
			ftp.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static FTPClient getFtp() {
		return ftp;
	}

	public InputStream getFileStream(String path){
		InputStream file=null;
		try {
			disconnect();
			connect();
			file=ftp.retrieveFileStream(path);

		} catch (Exception e) {

			e.printStackTrace();
		}
		return file;

	}

	public String getFileString(String path){
	     InputStream in = getFileStream(path);

        InputStreamReader is = new InputStreamReader(in);
        StringBuilder sb=new StringBuilder();
        BufferedReader br = new BufferedReader(is);
		try {
			String read = br.readLine();
			 while(read != null) {
		            sb.append(read).append(System.getProperty("line.separator"));

		            read =br.readLine();
		        }
		} catch (IOException e) {
			e.printStackTrace();
		}

		return sb.toString();
	}

	public void send(String path, String file, boolean backup) throws SocketException, IOException {
		disconnect();
		connect();

		if (backup) {
			ftp.rename(path, path + "_easybouquets_"
					+ (new SimpleDateFormat("yyyyMMdd").format(new Date())));
		}

		ftp.storeFile(path,
				new ByteArrayInputStream(file.getBytes("ISO-8859-1")));

		disconnect();
	}

}
